//app.js
var util = require('utils/util.js');
// 全局变量app。app.coord = longitude + "," + latitude。app.nickName = nickName。
var coord = "开始采集坐标";
// 网关服务地址
var gateUrl = util.getGPSDomain() + '/wxweb/weixin'
var nickName = "";
var lastX = 0;
var lastY = 0;
var uploadGPSOnHideTimer = null;
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  onHide: function () {
    console.log("onHide");
    util.logToServer('test', 'onHide')
    uploadGPSOnHideTimer = setInterval(uploadGPS, 30 * 1000);
  },
  onError: function (e) {
    console.log("app onError")
    util.logToServer('test', 'onError')
  },
  onShow: function () {
    console.log("onShow");
    util.logToServer('test', 'onShow')
    if (uploadGPSOnHideTimer != null) {
      clearInterval(uploadGPSOnHideTimer)
    }
    uploadGPSOnHideTimer = null
  },
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function (data) {
          // 设置全局变量
          var app = getApp()
          var platform = null
          wx.getSystemInfo({
            success: function (res) {
              // 基础版本号
              app.SDKVersion = res.SDKVersion
              // 平台
              app.platform = res.platform
            },
          })

          // console.log("code = " + data.code)
          wx.getUserInfo({
            success: function (loginResult) {
              // var encryptedData = loginResult.encryptedData
              // console.log("encryptedData = " + encryptedData)
              // var iv = loginResult.iv
              // console.log("iv = " + iv)
              that.globalData.userInfo = loginResult.userInfo
              // console.log('loginResult.userInfo.nickName=' + loginResult.userInfo.nickName)
              nickName = loginResult.userInfo.nickName;
              typeof cb == "function" && cb(that.globalData.userInfo)

              app.coord = "0,0"
              app.nickName = nickName
              app.reuploadGps = new Array()

              // 定时上传坐标
              uploadGPS()
              var timer = setInterval(uploadGPS, 30 * 1000);

              // 登陆服务器
              loginToServer()
            }
          })
        },
        fail: function () {
          // 设置全局变量
          var app = getApp()
          var msg = '【同意微信授权后才能正常使用~】'
          app.indexPage.setData({ coord: msg });
        }
      })
    }
  },
  globalData: {
    userInfo: null
  }
})

function uploadGPS() {
  wx.getLocation({
    type: 'gcj02',
    success: function (locationData) {
      var latitude = locationData.latitude
      var longitude = locationData.longitude
      // 存入全局变量
      var app = getApp()
      app.coord = longitude + "," + latitude
      // console.log("coord = " + app.coord)
      var accuracy;
      if (locationData.accuracy) {
        accuracy = locationData.accuracy;
      } else {
        accuracy = -1;
      }
      var time = util.formatTime(new Date())
      // console.log("data:" + longitude + "," + latitude + "," + accuracy + "," + time)

      // 是否坐标精度
      if (accuracy >= 0 && app.platform != 'devtools') {
        var groupId = ''
        var phone = ''
        if (app.phone) {
          phone = app.phone
        }
        if (app.groupId) {
          // 优先从内存对象取值
          groupId = app.groupId
        } else {
          // 再从系统缓存里取值
          var groutInfo = util.getStorage('groutInfo')
          if (groutInfo != null) {
            groupId = groutInfo.groupId
            // 取groupId的时候也取phone
            phone = groutInfo.phone
          }
        }
        console.log("(gpsData)groupId=" + groupId)
        var gpsData = longitude + "^" + latitude + "^" + accuracy + "^" + time + "^" + groupId + "^" + phone;
        var gpsDatas;
        if (app.reuploadGps.length == 0) {
          gpsDatas = gpsData;
        } else {
          gpsDatas = "";
          var i;
          for (i = 0; i < app.reuploadGps.length; i++) {
            gpsDatas += app.reuploadGps[i] + "__";
          }
          gpsDatas += gpsData;
        }
        // 上传坐标
        wx.request({
          url: gateUrl,
          data: {
            a: nickName,
            g: gpsDatas
          },
          success: function (uploadGPSResult) {
            console.log("success:" + uploadGPSResult.data)
            if (!uploadGPSResult.data.indexOf("成功")) {
              console.log("记录补传数据")
              app.reuploadGps[app.reuploadGps.length] = gpsData
            } else {
              // 上传成功后清理补传数据
              app.reuploadGps = new Array()
            }
          },
          fail: function (uploadGPSFailedResult) {
            util.logToServer(app.nickName, 'uploadGPSFailed')
            console.log("fail:" + uploadGPSFailedResult);
            console.log("记录补传数据")
            app.reuploadGps[app.reuploadGps.length] = gpsData
          }
        });
      } else {
        console.log("不上传坐标。accuracy=" + accuracy + ",platform=" + app.platform + "。");
      }
    },
    fail: function (e) {
      var app = getApp()
      app.coord = "0,0"
      console.log('getLocation fail:' + e.detail)
    }
  })
}

function loginToServer() {
  return
  // console.log('nickName=' + nickName)
  // 登陆服务器
  // wx.request({
  //   url: gateUrl,
  //   data: {
  //     a: nickName,
  //     cmd: 'login'
  //   },
  //   success: function (res) {
  //     console.log('loginToServer success. result=' + res.data.rights)
  //     // 存入全局变量
  //     var app = getApp()
  //     app.rights = res.data.rights
  //   },
  //   fail: function (error) {
  //     console.log('loginToServer fail')
  //   }
  // })
}